from email.mime.text import MIMEText
import smtplib
import subprocess
import os
from datetime import datetime, time

__author__ = 'chixq'


def send_mail(content):
    sender = "314300889@qq.com"
    receiver = ["zhouboyan@ench.cn"]
    host = 'smtp.qq.com'
    port = 465
    msg = MIMEText(content)
    msg['From'] = sender
    msg['To'] = ",".join(receiver)
    msg['Subject'] = "Weblogic error warning"
    try:
        smtp = smtplib.SMTP_SSL(host, port)
        smtp.login(sender, 'YOUR_SENDER_PASSWORD')
        smtp.sendmail(sender, receiver, msg.as_string())
        print("send email success")
    except Exception, e:
        print(e)


def get_current_offset(file_path):
    if not os.path.exists('/var/log/weblogic_log_offset'):
        offset_f = open('/var/log/weblogic_log_offset', 'w')
        try:
            process = subprocess.Popen('wc -l {0} | awk \'{print $1}\''.format(file_path), stdout=subprocess.PIPE,
                                       shell=True)
            if not process.stderr:
                offset_f.write(process.stdout.read())
            else:
                exit(1)
        except Exception, e:
            print(e)
        finally:
            offset_f.close()

    current_offset = int(open('/var/log/weblogic_log_offset', 'r').readline())
    return current_offset


def set_current_offset(offset):
    offset_f = open('/var/log/weblogic_log_offset', 'w')
    try:
        offset_f.write(offset)
    except Exception, e:
        print(e)
    finally:
        offset_f.close()
    pass


def grep_log(file_path):
    current_offset = get_current_offset(file_path)
    to_check_logs = open(file_path).readlines()[current_offset - 1:]

    match_err = 'which is more than the configured time (StuckThreadMaxTime) of "600" seconds.'
    match_jsp = 'Referer: http://'
    if match_err in to_check_logs and match_jsp in to_check_logs:
        print("600 Error caught! Sending Email...")
        now = time.mktime(datetime.now().timetuple())
        current_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(now))
        jsp_location = 'Not found'
        for line in to_check_logs:
            if match_jsp in to_check_logs:
                jsp_location = line
                break
        send_mail("600 Error caught at {0}, Error JSP: {1}".format(current_time, jsp_location))
        print

        new_offset = subprocess.Popen('wc -l {0} | awk \'{print $1}\''.format(file_path), stdout=subprocess.PIPE,
                                      shell=True).stdout.read()
        set_current_offset(new_offset)
    else:
        print("No Error found. Pass")
    pass


if __name__ == '__main__':

    grep_log(file_path='/bea/user_projects/domains/base_domain/servers/AdminServer/logs/base_domain.log')
